package com.ayf.payment.game.api.task.merchantTwo;

import com.ayf.payment.game.api.dto.ayb.SignPayProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.dto.sign.MerchantTwoSelectReqDTO;
import com.ayf.payment.game.api.dto.sign.MerchantTwoUpdateReqDTO;
import com.ayf.payment.game.api.service.SignPayProductService;
import com.ayf.payment.game.api.service.platform.PaymentChannelService;
import com.ayf.payment.game.api.service.sign.MerchantTwoSignService;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import com.swwx.charm.zookeeper.lock.DistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: 分账-二级商户状态查询
 * @Author: zh-liang
 * @Date : 2022-03-14
 */
@Component
public abstract class MerchantTwoStatusSelectTaskImpl {

    @Autowired
    private SignPayProductService signPayProductService;
    @Autowired
    private MerchantTwoSignService merchantTwoSignService;
    @Autowired
    private PaymentChannelService paymentChannelService;

    protected void run(DistributedLock distributedLock) {
        boolean lock = false;
        String traceId = SnowFlakeUtils.getTraceId();
        String lockName = this.getClass().getSimpleName().concat(System.getenv("XY_GAME_PAY_LOCK_FLAG"));
        try {
            if (lock = distributedLock.getLock(lockName)) {
                LogPortal.info("{} >>> get lock and run {} ", traceId, lockName);
                long count = 0;
                final int pageSize = 100;
                PageHelper.startPage(1, pageSize);
                List<SignPayProductDTO> dtoList = signPayProductService.litReviewSignPayProduct();
                PageInfo<SignPayProductDTO> pageInfo = new PageInfo<>(dtoList);
                count = pageInfo.getTotal();
                LogPortal.info("{} >>> [{}]处理总条数[{}]", traceId, lockName, count);
                if (count <= 0) {
                    return;
                }
                long totalPage = count % pageSize == 0 ? (count / pageSize) : (count / pageSize) + 1;
                for (int i = 0; i < totalPage; i++) {
                    PageHelper.startPage(i + 1, pageSize);
                    final List<SignPayProductDTO> list = signPayProductService.litReviewSignPayProduct();
                    LogPortal.info("{} >>> {} 开始处理处理中的-分账-二级商户状态-查询第[{}]页[{}]条记录", traceId, lockName, (i + 1), list.size());
                    //初始化信号
                    final CountDownLatch countDownLatch = new CountDownLatch(list.size());
                    for (final SignPayProductDTO dto : list) {
                        submit(new Runnable() {
                            @Override
                            public void run() {
                                PaymentChannelDTO channel = paymentChannelService.getPaymentChannelByCode(dto.getPayCode());
                                try {
                                    MerchantTwoSelectReqDTO reqDTO = new MerchantTwoSelectReqDTO();
                                    reqDTO.setChannelCode(channel.getCode());
                                    reqDTO.setMerchantId(dto.getMerchantId());
                                    merchantTwoSignService.merchantTwoSelect(reqDTO);
                                } catch (Exception e) {
                                    LogPortal.error("{} 商户ID[{}] 渠道code[{}] 渠道name[{}] 分账-二级商户状态查询-发生了{}异常，错误描述:{}", traceId, dto.getMerchantId(), channel.getCode(), channel.getName(), e.getClass().getName(), e.getMessage());
                                } finally {
                                    //线程执行完成之后标记信号表示完成
                                    countDownLatch.countDown();
                                }
                            }
                        });
                    }
                    //等待线程池任务执行完毕
                    countDownLatch.await();
                }
            } else {
                LogPortal.info("{} >>> {} do not get lock ", traceId, lockName);
            }
        } catch (GetLockFailedException e) {
            LogPortal.error("{} >>> [DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", traceId, lockName);
            LogPortal.error("{} >>> {} 获取lock失败", e, traceId, lockName);
        } catch (Exception e) {
            LogPortal.error("{} >>> {} 任务执行出错 ", e, traceId, lockName);
        } finally {
            if (lock) {
                LogPortal.info(traceId + " >>> " + lockName + " finished.");
                try {
                    distributedLock.releaseLock(lockName);
                } catch (ReleaseLockFailedException e) {
                    LogPortal.error("{} >>> [DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}", traceId, lockName);
                    LogPortal.error("{} >>> {} 释放失败", e, traceId, lockName);
                }
            }
        }
    }

    public abstract void submit(Runnable task);
}
